﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GRTVPluginConsole.Entity;

namespace GRTVPluginConsole.Camera
{
    class CycleAllDriversCamera : AutoCameraEngine
    {
        int viewedSlotId = -1;
        int cameraType;
        bool excludePit;
        int frequencySecond;
        long lastCameraChange;
        public CycleAllDriversCamera(int cameraType, bool excludePit, int frequencySecond)
            : base()
        {
            this.cameraType = cameraType;
            this.excludePit = excludePit;
            this.frequencySecond = frequencySecond;
        }

        public override void DoCheck()
        {
            if (DateTime.Now.Ticks - lastCameraChange >= frequencySecond * 10000000)
            {
                if (Program.DriverList.Count > 0) {
                    lastCameraChange = DateTime.Now.Ticks;
                    // search current viewed driver index
                    int currentIndex = -1;
                    for (int i = 0; i < Program.DriverList.Count; i++)
                    {
                        DriverRank dr = Program.DriverList[i];
                        if (dr != null && viewedSlotId == dr.slotId) {
                            currentIndex = i;
                            break;
                        }
                    }
                    int nb = Program.DriverList.Count;
                    for (int i = 0; i < nb; i++)
                    {
                        currentIndex++;
                        DriverRank dr = Program.DriverList[currentIndex % nb];
                        if (dr != null && (!excludePit || !dr.isInPit) && dr.finishStatus <= 1)
                        {
                            viewedSlotId = dr.slotId;
                            Program.ViewDriver(viewedSlotId, cameraType);
                            break;
                        }
                    }
                }
            }
        }

        public override void Reset()
        {
            viewedSlotId = -1;
            lastCameraChange = 0;
        }
    }
}
